package aml.parse.node;

import aml.runtime.Context;
import aml.runtime.Method;
import aml.runtime.Value;

public class OpAutoSend extends OpNode {

	@Override
	public int precedence() {
		return 1000000;
	}
	
	@Override
	public Value eval(Context ctx) {
		Value ret = null;
		
		boolean topLevel = false;
		if (ctx.isTopLevel()) {
			topLevel = true;
			ctx.clearTopLevel();
		}
		
		Value left = lhs.eval(ctx);
		if (left instanceof Method) {
			if (rhs instanceof Tuple) {
				ret = ((Method) left).apply(ctx, new Value[]{((Tuple) rhs).makeTuple(ctx)});
			}
			else {
				ret = ((Method) left).apply(ctx, new Value[]{rhs.eval(ctx)});	// TODO
			}
		}
		else {
			ret = left.call(ctx, "(apply)", new Value[]{rhs.eval(ctx)});
		}
		
		if (topLevel) {
			ctx.setTopLevel();
			ctx.clearReturnFlag();
		}
		
		return ret;
	}

	@Override
	public String toString() {
		return "(A " + lhs + " " + rhs + ")";
	}
	
}